package thread;

import 网络编程.MyServerSocket;

import java.io.*;
import java.net.Socket;
import java.util.stream.Stream;

public class ServerThread extends Thread {
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;

    }

    @Override
    public void run() {

        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while (true) {
                try {
                    String msg =  dataInputStream.readUTF();
                    sendMsgToAll(msg);
                    System.out.println(socket.getRemoteSocketAddress() + ": " + msg);
                } catch (Exception e) {
                    System.out.println(socket.getRemoteSocketAddress() + " 下线了");
                    MyServerSocket.onLineSockets.remove(socket);
                    dataInputStream.close();
                    socket.close();
                    break;
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void sendMsgToAll(String msg) throws IOException {
        for (Socket onLineSocket : MyServerSocket.onLineSockets) {
            OutputStream outputStream = onLineSocket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(onLineSocket.getRemoteSocketAddress() + ": " + msg);
            outputStream.flush();
        }
    }
}
